#include "../include/parser.h"
#include"../include/retrievejson.h"
#include"../include/reader.h"
#include"../include/value.h"
namespace Json {
	Parser::Parser(const string& sn)
	{
		_sn=sn;
		parse();
	}


	Parser::~Parser()
	{
	}

	void Parser::parse()
	{
		_json=RetrieveJson::retrieveJson(_sn);
		if(_json.empty())
			return;
		Json::Value root;
		Json::Reader reader;
		bool ok=reader.parse(_json,root);
		if(!ok)
		{
			cout<<"Parse Json Failed.\n"
				<<reader.getFormattedErrorMessages();
			return;
		}
		bool result=root.get("result","false").asBool();
		if(result)
		{
			char buf[BUFFER_SIZE];
			_a.content["result"]="true";
			string name=root["app"]["name"].asString();
			_a.content["name"]=name;
			string vstamp=root["app"]["vstamp"].asString();
			_a.content["vstamp"]=vstamp;
			int aid=root["app"]["aid"].asInt();;
			sprintf(buf,"%d",aid);
			_a.content["aid"]=buf;
			string code=root["app"]["code"].asString();
			_a.content["code"]=code;
			string icon=root["app"]["icon"].asString();
			bool ismax=root["app"]["ismax"].asBool();
			int w=root["app"]["width"].asInt();
			sprintf(buf,"%d",w);
			_a.content["width"]=buf;
			int h=root["app"]["height"].asInt();
			sprintf(buf,"%d",h);
			_a.content["height"]=buf;
			_a.content["ismax"]=ismax?"true":"false";
			string url=root["app"]["url"].asString();
			_a.content["url"]=url;
			_a.content["icon"]=icon;
			const Json::Value exs=root["extension"];
			for(int i=0;i<static_cast<int>(exs.size());i++)
			{	
				extension e;
				e.clear();
				const Json::Value ex=exs[i];
				string exName=ex.get("name","Unknown Name").asString();
				string exVersion=ex.get("version","1.0.0").asString();
				string exUrl=ex["url"].asString();
				string exDescription=ex["description"].asString();
				e.content["name"]=exName;
				e.content["version"]=exVersion;
				e.content["url"]=exUrl;
				e.content["description"]=exDescription;
				_a.extensions.push_back(e);
			}
			_a.extensionNum=exs.size();
		}
		else
			_a.content["result"]="false";
	}

	list<extension> Parser::getExtensions() const
	{
		return _a.extensions;
	}

	app Parser::getApp() const
	{
		return _a;
	}
	string Parser::getJson()const
	{
		return _json;
	}

	void Parser::setSn(const string &sn)
	{
		_sn=sn;
	}
}